//
//  MyCollectionTableViewController.swift
//  SCUTWiki
//
//  Created by Wu Weisong on 2020/12/12.
//  Copyright © 2020 wwszhw. All rights reserved.
//

import UIKit

class MyCollectionTableViewController: UITableViewController, UISearchResultsUpdating, UISearchControllerDelegate, StarDelegate {

    let searchController = UISearchController(searchResultsController: nil)
    let myRefreshControl = UIRefreshControl()
    
    let sqlManager = SQLiteManager.shareInstance
    var articlesArray = [ArticleModel]()
    var searchResults = [ArticleModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        searchController.delegate = self //将self作为回调对象
        searchController.obscuresBackgroundDuringPresentation = false//气死了，设置在搜索时view的r内容不被隐藏（即可点击，不然搜索出来的结果不能点击），设置此属性默认不掩盖背景
        searchController.searchResultsUpdater=self
        searchController.searchBar.searchBarStyle = UISearchBar.Style.minimal//设置bar的样式
        self.tableView.tableHeaderView = searchController.searchBar//设置bar到tableview的第一项
        definesPresentationContext = true //坑，暂时不太懂，但是不设置会导致搜索状态下切换到其他页面后回来页面黑屏
        
        myRefreshControl.addTarget(self, action: #selector(refreshHeader), for: .valueChanged)
        myRefreshControl.attributedTitle = NSAttributedString(string: "下拉刷新数据")
        self.tableView.addSubview(myRefreshControl)
        
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(false)
        if let select_index = tableView.indexPathForSelectedRow, articlesArray[select_index.row].collected == false{//如果被选中的行取消收藏则从收藏列表去除该行
            self.tableView.beginUpdates()
            articlesArray.remove(at: select_index.row)
            self.tableView.deleteRows(at: [select_index], with: .fade)
            self.tableView.endUpdates()
        }else{
            loadData()
            self.tableView.reloadData()
        }
        
    }
    
    // MARK: - Table view data source
    func loadData()-> Void{
        articlesArray.removeAll()
        if sqlManager.openDB()==true{
            if let articles = sqlManager.execQuerySQL(sql: "select * from articles where collected = true"){
                for (_,row) in articles.enumerated(){
                    articlesArray.append(ArticleModel(rowData: row))
                }
            }else{
                articlesArray.append(ArticleModel(id:-1, title: "暂无该内容的无数据", content: "暂无该内容的无数据", type_id: -1, collected: false))
            }
            sqlManager.closeDB()
        }
    }
    
    @objc func refreshHeader(){
        loadData()
        self.tableView.reloadData()
        myRefreshControl.endRefreshing()
    }
    
    func updateSearchResults(for searchController: UISearchController) {
        //去除头尾的空格
        let whitespaceCharacterSet = CharacterSet.whitespaces
        let strippedString = searchController.searchBar.text!.trimmingCharacters(in: whitespaceCharacterSet)
        let searchItems = strippedString
        
        searchResults.removeAll()
        for row in articlesArray{
            if row.title.contains(searchItems){
                searchResults.append(row)
            }
        }
        
        self.tableView.reloadData()
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if searchController.isActive{
            return searchResults.count
        }else{
            return articlesArray.count
        }
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCollectionTableViewCell", for: indexPath)

        // Configure the cell...
        if searchController.isActive{
            cell.textLabel?.text = searchResults[indexPath.row].title
        }else{
            cell.textLabel?.text = articlesArray[indexPath.row].title
        }

        return cell
    }
 

    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if let dest_view_controller = segue.destination as? ArticleViewController{
            if let select_index = self.tableView.indexPathForSelectedRow?.row{
                dest_view_controller.articleObject = self.articlesArray[select_index]
                dest_view_controller.starDelegate = self
            }
        }
    }
    
    //用户更改收藏，更新tableview的datasource和db
    func changeCollection(collected: Bool) {
        if let select_index = self.tableView.indexPathForSelectedRow{
            updateData(index: select_index.row)
            articlesArray[select_index.row].collected = collected
        }
    }
    
    func updateData(index:Int) -> Void {
        if sqlManager.openDB(){
            if sqlManager.execUpdateSQL(sql: "update articles set collected=\(articlesArray[index].collected) where id=\(articlesArray[index].id)"){
                print("collect tableview 更改db收藏")
            }
        }
        sqlManager.closeDB()
    }
    
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            articlesArray.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    
    /*
     // Override to support conditional editing of the table view.
     override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
     // Return false if you do not want the specified item to be editable.
     return true
     }
     */
    
    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    

 
}
